
import { _decorator, Component, Enum, ProgressBar, Label, resources, AssetManager, SpriteFrame } from 'cc';
import { CustomEventListener } from '../data/CustomEventListener';
import { E2LProtocol, L2EProtocol } from '../proto/ELProtocol';
const { ccclass, property } = _decorator;

enum LOAD_TYPE {
    login = 1,
    loadGame,
    loadHall,
};
Enum(LOAD_TYPE);
 
@ccclass('Loading')
export class Loading extends Component {
    @property({
        type: LOAD_TYPE,
    })
    private loadType = LOAD_TYPE.login;

    @property({
        type: ProgressBar,
    })
    private progressBar = null;

    @property({
        type: Label,
    })
    private info = null;

    private targetPer: number;
    private currPer: number;
    
    onEnable() {
        this.targetPer = 0;
        this.progressBar.progress = 0;
        this.info.string = "加载中"; 
         
        // resources.load("",
        //     (finished: number, total: number, item: AssetManager.RequestItem)=>{

        //     }, 
        //     (err: Error | null, data: SpriteFrame)=>{

        //     })
        CustomEventListener.on(L2EProtocol.l2e_update_loading, this.setTargetProgress.bind(this), this);
        CustomEventListener.on(L2EProtocol.l2e_hide_load, this.closeSelf.bind(this), this);

        CustomEventListener.dispatchEvent(E2LProtocol.e2l_start_load);
    }

    onDisable() {
        CustomEventListener.off(L2EProtocol.l2e_update_loading, this.setTargetProgress.bind(this));
        CustomEventListener.off(L2EProtocol.l2e_hide_load, this.closeSelf.bind(this));
    }


    update (deltaTime: number) {
        if (this.targetPer > this.currPer) {
            this.currPer += deltaTime;
            this.currPer = Math.min(100, this.currPer);
            this.progressBar.progress = this.currPer/100;
            this.info.string = "正在加载资源文件... "+(this.currPer.toFixed(1))+"%";
        }

        if (this.currPer ===  100) {
            CustomEventListener.dispatchEvent(E2LProtocol.e2l_load_complete);
        }

    }

    public setTargetProgress(current: number, total: number) {
        this.targetPer = current*100.0/total;
    }

    public closeSelf() {
        this.enabled = false;
    }
}

